package com.healthlink.appcloudcalllib.keeplive;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.healthlink.appcloudcalllib.callback.MessageCallBack;
import com.healthlink.appcloudcalllib.common.Constants;
import com.healthlink.appcloudcalllib.databean.MqttInfoBean;
import com.healthlink.appcloudcalllib.net.OKCallback;
import com.healthlink.appcloudcalllib.net.OkUtils;
import com.healthlink.appcloudcalllib.utils.Out;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 保活监听mqtt
 */
public class KeepLiveMqttService extends Service {


    Timer timer ;
    TimerTask timerTask ;
    Context context;
    int time=0;
    private String appId;
    private String host;
    private String sn;
    private String accessToken;
    private int type=0;
    Handler hd;
    private MyReceiver myReceiver;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            time++;
            try{
                boolean isConnect= sampleClient.isConnected();
                if (time%3==0){
                    Out.out2("连接状态："+isConnect+"==="+time+"====configtime="+Constants.MQTTTIME);

                }
                if (!isConnect){

                    if (time>=Constants.MQTTTIME){
                        doCancleTopic();
                    }
                    try {
                        sampleClient.unregisterResources();
                    }catch (Exception exception){}
                    hd.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                sampleClient.close();
                            }catch (Exception ee){}

                            try {
                                if (Out.getNetWorkStatus(context)){
                                    try {
                                        timer.cancel();
                                    }catch (Exception exception){}
                                    try {
                                        timer=null;
                                    }catch (Exception exception){}
                                    try {
                                        timerTask.cancel();
                                    }catch (Exception exception){}
                                    try {
                                        timerTask=null;
                                    }catch (Exception exception){}
                                    initMqtt();
                                    Out.out("开始初始化mq");
                                }
                            }catch (Exception exception){
                                exception.printStackTrace();
                                Out.out("mqeroor=="+exception.getMessage());
                            }
                        }
                    },100);


                }
                if (time> Constants.MQTTTIME){
                    Out.out2("时间到点停止监听");
                    doCancleTopic();
                    try{
                        timer.cancel();
                        timer=null;
                    }catch (Exception exception){}
                    try{
                        timerTask.cancel();
                        timerTask=null;
                    }catch (Exception exception){}
                }
            }catch (Exception exception){}

        }
    };
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        context=this;
        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.bjym.callmethod");
        registerReceiver(myReceiver, filter);



    }
    MqttAndroidClient sampleClient;
    private void subjectTopic(String topic) {
        try {
            if (sampleClient==null||Constants.MQTTTOPIC==null){

            }else{
                sampleClient.subscribe(topic, 0);
            }

        } catch (MqttException e) {
            e.printStackTrace();
        }catch (Exception ex){}
    }
    public void doCancleTopic(){

        try {
            if (sampleClient==null||Constants.MQTTTOPIC==null){

            }else{
                if (!TextUtils.isEmpty(Constants.MQTTTOPIC)){

                        sampleClient.unsubscribe(Constants.MQTTTOPIC);


                }

            }

        } catch (MqttException e) {
            e.printStackTrace();
        }catch (Exception ee){
            ee.printStackTrace();
        }
    }
    private MqttConnectOptions createConnectOptions(String userName, String passWord) throws NoSuchAlgorithmException, InvalidKeyException {
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(userName);
        connOpts.setPassword(passWord.toCharArray());
        connOpts.setAutomaticReconnect(true);
        // 设置连接超时时间, 单位为秒,默认30
        connOpts.setConnectionTimeout(30);
        // 设置会话心跳时间,单位为秒,默认20
        connOpts.setKeepAliveInterval(20);
        return connOpts;
    }
    private void initMqtt() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                hd.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (sampleClient!=null){
                                try {

                                    doCancleTopic();
                                }catch (Exception exception){}
                                try {
                                    sampleClient.unregisterResources();
                                }catch (Exception exception){}
                                Thread.sleep(100);
                                try {
                                    sampleClient.close();
                                }catch (Exception exception){}
                                try {
                                    sampleClient.disconnect();
                                }catch (Exception exception){}

                                sampleClient=null;

                            }
                        }catch (Exception e){}
                        String typeStr="";
                        if (type==3){
                            typeStr="1";
                        }else {
                            typeStr=type+"";
                        }
                        Out.out("开始请求MQ："+appId);

                        Constants.logs.add("获取mq配置："+System.currentTimeMillis());
                        doSendMsg("获取mq配置："+System.currentTimeMillis());
                        OkUtils.GetOk(Constants.GetMqttInfo+"app_id="+appId+"&serial_number="+ sn+"&type="+typeStr,accessToken,new OKCallback(context){
                            @Override
                            public void Sucess(String str) {
                                super.Sucess(str);
                                MqttInfoBean mqttInfoBean= JSON.parseObject(str,MqttInfoBean.class);
//                                if (mqttInfoBean.connectLong==0){
//                                    return;
//                                }

                                doSendMsg("获取mq配置返回："+System.currentTimeMillis());
                                Constants.logs.add("获取mq配置返回："+System.currentTimeMillis());
                                sampleClient = new MqttAndroidClient(context, mqttInfoBean.url, mqttInfoBean.clientId);
                                //创建服务连接
                                try {
                                    MqttConnectOptions connOpts = createConnectOptions(mqttInfoBean.userName, mqttInfoBean.password);
                                    Constants.logs.add("mq开始连接："+System.currentTimeMillis());
                                    doSendMsg("mq开始连接："+System.currentTimeMillis());
                                    sampleClient.connect(connOpts, null, new IMqttActionListener() {
                                        @Override
                                        public void onSuccess(IMqttToken asyncActionToken) {
                                            //连接成功，需要上传客户端所有的订阅关系
                                            Constants.MQTTTIME=mqttInfoBean.connectLong;

                                            if (Constants.MQTTTIME==0){
                                                Out.out2("不进行连接！");
                                              return;
                                            }
                                            Constants.logs.add("mq连接成功："+System.currentTimeMillis());
                                            doSendMsg("mq连接成功："+System.currentTimeMillis());

                                            subjectTopic(mqttInfoBean.topic);
                                            Constants.MQTTTOPIC=mqttInfoBean.topic;
                                            if (type==1){
                                                Intent intent=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
                                                intent.putExtra("msg","ym101");
                                                intent.setPackage(getPackageName());//最好加上这句话
                                                sendBroadcast(intent);
                                            }
                                            if (type==3){
                                                Intent intent=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
                                                intent.putExtra("msg","ym103");
                                                intent.setPackage(getPackageName());//
                                                sendBroadcast(intent);
                                            }
                                            timer = new Timer();
                                            timerTask=new TimerTask() {
                                                @Override
                                                public void run() {
                                                    Message message=new Message();
                                                    message.what=1;
                                                    handler.sendMessage(message);

                                                }
                                            };

                                            timer.schedule(timerTask,1000,1000);
                                        }

                                        @Override
                                        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                                            Out.out("mqtt连接失败："+exception.getMessage());
                                        }
                                    });
                                } catch (MqttException e) {
                                    Out.out("MqttException="+e.getMessage());
                                    e.printStackTrace();
                                } catch (NoSuchAlgorithmException e) {
                                    Out.out("NoSuchAlgorithmException="+e.getMessage());
                                    e.printStackTrace();
                                } catch (InvalidKeyException e) {
                                    Out.out("InvalidKeyException="+e.getMessage());
                                    e.printStackTrace();
                                }catch (Exception ee){
                                    Out.out("mqeee="+ee.getMessage());
                                    ee.printStackTrace();
                                }

                                setListener();
                            }

                            @Override
                            public void Eorror(int code) {
                                super.Eorror(code);
                                Out.out2("请求203错误");
                                if (code==203){
                                    Intent intent=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
                                    intent.putExtra("msg","ym102");
                                    intent.setPackage(getPackageName());//最好加上这句话
                                    sendBroadcast(intent);
                                }

                            }
                        });
                    }
                });


            }
        }).start();


    }

    private void doSendMsg(String s) {
        Intent intent=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
        intent.putExtra("msg","showlogs@"+s);
        intent.setPackage(getPackageName());//最好加上这句话
        sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
//        try {
//            Intent intent=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
//            intent.putExtra("msg","ymdestory");
//            intent.setPackage(getPackageName());//最好加上这句话
//            sendBroadcast(intent);
//        }catch (Exception e){
//
//        }
        try {
            unregisterReceiver(myReceiver);
        }catch (Exception exception){}
        super.onDestroy();
        Out.out2("服务被关闭");

        time=0;
        try {
            timer.cancel();
            timer=null;
        }catch (Exception e){}

        try {
            timerTask.cancel();
            timerTask=null;
        }catch (Exception e){}
        try {
        doCancleTopic();
        }catch (Exception ee){}
        try {
            sampleClient.unregisterResources();
        }catch (Exception exception){}
        try {
            Thread.sleep(100);
            try {
                sampleClient.disconnect();
            }catch (Exception ee){}
            try {
                sampleClient.close();
            }catch (Exception ee){}
        } catch (InterruptedException e) {
            e.printStackTrace();
        }




        try{
            timer.cancel();
            timer=null;
        }catch (Exception exception){}
        try{
            timerTask.cancel();
            timerTask=null;
        }catch (Exception exception){}



    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            hd=new Handler();
            appId=intent.getStringExtra("appId");
            host=intent.getStringExtra("host");
            Out.out("KeepLiveMqttServiceAPPID=="+appId);
            Out.out("KeepLiveMqttServicehost=="+host);
            Constants.HOST=host;
            type=intent.getIntExtra("type",0);
            sn=intent.getStringExtra("sn");
            accessToken=intent.getStringExtra("astoken");
            initMqtt();
        }catch (Exception exception){
            Intent intent22=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
            intent22.putExtra("msg","servicekill");
            intent22.setPackage(getPackageName());//最好加上这句话
            sendBroadcast(intent22);
        }

        return super.onStartCommand(intent, flags, startId);


    }
    /**
     * mqtt监听
     */
    private void setListener() {

        sampleClient.setCallback(new MqttCallback() {
            @Override//连接丢失后，会执行这里
            public void connectionLost(Throwable throwable) {
            }

            @Override//获取的消息会执行这里--arg0是主题,arg1是消息
            public void messageArrived(final String ssr, MqttMessage mqttMessage) throws Exception {



                 String mqtt_message = mqttMessage.toString();//消息
                Intent intent=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
                intent.putExtra("msg",mqtt_message);
                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                intent.setPackage(getPackageName());//最好加上这句话
                sendBroadcast(intent);
            }

            @Override//订阅主题后会执行到这里
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {


            }
        });

    }
    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String msg=intent.getStringExtra("msg");
                String token=intent.getStringExtra("token");
                accessToken=token;

                if (msg.equals("acceptcallin@")){
                    time=0;
                    if (Constants.MQTTTIME-time>10){
                        doRestTime(1);
                    }else{
                        try {
                            timer.cancel();
                        }catch (Exception exception){}
                        try {
                            timer=null;
                        }catch (Exception exception){}
                        try {
                            timerTask.cancel();
                        }catch (Exception exception){}
                        try {
                            timerTask=null;
                        }catch (Exception exception){}
                        initMqtt();
                    }

                }
                if (msg.equals("guaduan@")){
                    time=0;
                    if (Constants.MQTTTIME-time>10){
                        doRestTime(2);
                    }else{
                        try {
                            timer.cancel();
                        }catch (Exception exception){}
                        try {
                            timer=null;
                        }catch (Exception exception){}
                        try {
                            timerTask.cancel();
                        }catch (Exception exception){}
                        try {
                            timerTask=null;
                        }catch (Exception exception){}
                        initMqtt();
                    }

                }
            }catch (Exception exception){

            }



        }
    }

    private void doRestTime(int type2) {
        OkUtils.GetOk(Constants.GetMqttInfo+"app_id="+appId+"&serial_number="+ sn+"&type="+type2,accessToken,new OKCallback(context){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                MqttInfoBean mqttInfoBean= JSON.parseObject(str,MqttInfoBean.class);
                Constants.MQTTTIME=mqttInfoBean.connectLong;
                if (type2==1){
                    Intent intent=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
                    intent.putExtra("msg","ym103");
                    intent.setPackage(getPackageName());//
                    sendBroadcast(intent);
                }
            }

            @Override
            public void Eorror(int code) {
                super.Eorror(code);

                if (code==203){
                    Intent intent=new Intent("com.healthlink.appcloudcalllib.keeplive.MsgReceiver.MY_BROADCAST");//其中的action依然是我自定义的
                    intent.putExtra("msg","ym104");
                    intent.setPackage(getPackageName());//最好加上这句话
                    sendBroadcast(intent);
                }

            }
        });
    }
}
